package com.wwg.myapplication;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.os.SystemProperties;
import android.widget.Toast;

import com.skg.services.manager.SkgSettingsManager;
import com.skg.services.manager.SkgMultipleUsersManager;
import com.skg.tools.MyWindowManager;
import com.skg.tools.app.ToolApplication;
import com.skg.tools.freeze.FreezeWindowManager;
import com.skg.tools.gestures.GestureSwipeUpHelper;
import com.skg.tools.lock.NumberPassWord;
import com.skg.tools.lock.TouchLockView;
import com.skg.tools.screenshot.FullScreenShotActivity;
import com.skg.tools.service.*;
import com.skg.tools.whitefield.WhiteFieldActivity;

import android.provider.Settings;

import com.skg.tools.devices.*;
import com.skg.tools.R;

import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.content.ComponentName;

public class MyBroadcast extends BroadcastReceiver {

    private static final String TAG = "SkgMyBroadcast";
    public static String CLEAN_START_BROAD_CAST = "com.skg.start.cleantask";
    public static String CALCULATOR_START_BROAD_CAST = "com.skg.start.calculator";
    private static final String ACTION_SHOW_LOCKSCREEN = "com.skg.lockscreen_show";
    //private static final String ACTION_GONE_LOCKSCREEN = "com.skg.lockscreen_gone";

    private static final String ACTION_SHOW_COUNTDOWN = "com.skg.countdown_show";
    private static final String ACTION_GONE_COUNTDOWN = "com.skg.countdown_gone";
    private static final String ACTION_VOICE_RECORDER = "com.skg.voice_record";

    private static final String ACTION_BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";
    private static final String ACTION_SHOW_TEMPERATURE = "com.skg.temperature_show";
    private static final String ACTION_GONE_TEMPERATURE = "com.skg.temperature_gone";

    private static final String ACTION_SHOW_BACKLIGHT_COVER = "com.skg.show_backlight_cover";
    private static final String ACTION_HIDE_BACKLIGHT_COVER = "com.skg.hide_backlight_cover";

    private static final String ACTION_TOUCH_LOCK_OPEN = "com.skg.menu_ui.touch_lock_open";
    private static final String ACTION_TOUCH_LOCK_CLOSE = "com.skg.menu_ui.touch_lock_close";

    private static final String ACTION_CONNECT_NETWORK = "com.skg.connect_network";

    private static final String ACTION_AB_WHITE_FIELD_ENTER = "com.skg.command.ab.white_field.enter";
    private static final String ACTION_AB_WHITE_FIELD_EXIT = "com.skg.command.ab.white_field.exit";

    private static final String CAM_HUB_RESET_PROPERTY = "com.skg.command.cam.hub";
    private static final String CAM_HUB_PROPERTY_PERMIT = "permit";
    private static final String CAM_HUB_PROPERTY_PREVENT = "prevent";
    private static final String CAM_HUB_CAMERA_PROPERTY = "com.skg.command.camera_hub";
    private static final String CAM_HUB_CAMERA_PROPERTY_OPEN = "openOnceCamera";

    private static final String ACTION_SHOW_SYSTEM_AUTIBURN = "com.skg.system.autiburn_start";

    private static final String ACTION_START_FREEZE = "com.skg.freeze_start";
    private static final String ACTION_STOP_FREEZE = "com.skg.freeze_stop";
    private static final String ACTION_SHOW_GESTURE_SWIPEUP = "com.skg.tools.action.SHOW_GESTURE_SWIPEUP";
    private static final String ACTION_CLEAR_GESTURE_SWIPEUP = "com.skg.tools.action.CLEAR_GESTURE_SWIPEUP";
    private static final String SHOW_GLOBAL_GESTURES = "persist.sys.should_show_global_gestures";
    private static final String ACTION_FULL_SCREENSHOT = "com.skg.full_screenshot";
    private static final String ACTION_SPOTLIGHT_LONGPRESS = "com.skg.pen.spotlight_longpress";

    private static final int MSG_TOAST = 101;

    private Thread mProjectionThread;//投屏器插入情况检测是否打开相机线程
    private static boolean mIsProjectionThreadRun = true;//投屏器检测进程是否运行

    CameraDeviceDialog cameraSelector;

    // 添加时间戳，用于防抖
    private static long lastBurnTime = 0;
    private static final long BURN_DELAY = 1000; // 1秒内只处理一次

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage what = " + msg.what + ", ToolApplication.getInstance() = " + ToolApplication.getInstance());
            switch (msg.what) {
                case MSG_TOAST:
                    if (ToolApplication.getInstance() != null) {
                        Toast.makeText(ToolApplication.getInstance(), "" + msg.obj, Toast.LENGTH_LONG).show();
                    }

                    break;
            }
        }
    };

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.e(TAG, " --- action ---  " + action);
        if (CLEAN_START_BROAD_CAST.equals(action)) {
            MyWindowManager.createSkgClean(context);
        } else if (CALCULATOR_START_BROAD_CAST.equals(action)) {
            MyWindowManager.createCaculator(context, 0);
        } else if (ACTION_SPOTLIGHT_LONGPRESS.equals(action)) {
            MyWindowManager.spotLightLongPress(context);
        }
        /*
        else if (ACTION_SHOW_LOCKSCREEN.equals(action)) {
            int show_mode = NumberPassWord.PASSMODE_LOCK_NORMAL;
            if (intent.hasExtra("mode")) {
                show_mode = intent.getIntExtra("mode", NumberPassWord.PASSMODE_LOCK_NORMAL);
            }
            MyWindowManager.createNumberPassWord(context, show_mode);
        } else if (ACTION_GONE_LOCKSCREEN.equals(action)) {
            int gone_mode = NumberPassWord.PASSMODE_LOCK_NORMAL;
            if (intent.hasExtra("mode")) {
                gone_mode = intent.getIntExtra("mode", NumberPassWord.PASSMODE_LOCK_NORMAL);
            }
            MyWindowManager.removeNumberPassWord(context, gone_mode);
        }
         */
        else if (ACTION_SHOW_BACKLIGHT_COVER.equals(action)) {
            MyWindowManager.createBacklightCover(context);
        } else if (ACTION_HIDE_BACKLIGHT_COVER.equals(action)) {
            MyWindowManager.removeBacklightCover(context);
        } else if (ACTION_SHOW_COUNTDOWN.equals(action)) {
            MyWindowManager.createCountDown(context);
        } else if (ACTION_GONE_COUNTDOWN.equals(action)) {
            MyWindowManager.removeCountDown(context);
        } else if (ACTION_VOICE_RECORDER.equals(action)) {
            MyWindowManager.createRecord(context);
        } else if (ACTION_BOOT_COMPLETED.equals(action) || ACTION_SHOW_LOCKSCREEN.equals(action)) {
            // context.startService(new Intent(context, PopupController.class));
            // check in lock state
//            String strScreenLockSwitch = Settings.Global.getString(context.getContentResolver(), "screen_lock_switch");
            String strScreenLockSwitch = SystemProperties.get("persist.sys.skg.screen_lock_switch");
            boolean boolScreenLockSwitch = Boolean.parseBoolean(strScreenLockSwitch == null ? "false" : strScreenLockSwitch);
            Log.d(TAG, "strScreenLockSwitch = " + strScreenLockSwitch + ", boolScreenLockSwitch = " + boolScreenLockSwitch);
            if (boolScreenLockSwitch) {
                Intent lockIntent = new Intent(ScreenLockService.LOCK_ACTION);
                lockIntent.setClass(context, ScreenLockService.class);
                context.startService(lockIntent);
            }
            // 检测是否已插入投屏
            // checkProjectionMode(context);

            //开机判断润屏功能是否开启
            String protectBurnStatus = SystemProperties.get("persist.sys.skg.protect_burn", "3");
            if (!protectBurnStatus.equals("0")) {
                Intent timeIntent = new Intent();
                ComponentName mComponentName = new ComponentName("com.skg.tools", "com.skg.tools.service.BurnProtectService");
                timeIntent.setComponent(mComponentName);
                context.startService(timeIntent);
            }

        } else if (ACTION_SHOW_TEMPERATURE.equals(action)) {
            MyWindowManager.createTemperatureLayout(context);
        } else if (ACTION_GONE_TEMPERATURE.equals(action)) {
            MyWindowManager.removeTemperatureLayout(context);
        } else if (ACTION_TOUCH_LOCK_OPEN.equals(action)) {
            int position = intent.getIntExtra("position", TouchLockView.RIGHT_MODE);
            MyWindowManager.createTouchLockLayout(context, position);
        } else if (ACTION_TOUCH_LOCK_CLOSE.equals(action)) {
            MyWindowManager.removeTouchLockLayout(context);
        } else if ("skg.simplecamera.add".equals(action)) {
            // CameraDeviceDialog.DialogInstance.onIntent(context, intent);
        } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            Log.i(TAG, "ACTION_USB_DEVICE_DETACHED");
            UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (isToofifiDevice(usbDevice)) {
                cam_hub_reset();
                stopJudgeProjectMode(context);
            }
        } else if (ACTION_CONNECT_NETWORK.equals(action)) {
            //Utils.setStaticIP(context);
        } else if ("com.skg.blurwallpaper".equals(action)) {
            int temp = intent.getIntExtra("bgsource", 0);
            Log.d("SKGTools", "blur===get temp from broadcast: " + temp);
            String blurwallpaperpath = intent.getStringExtra("blurwallpaperpath");
            Log.d("SKGTools", "blur===get path from broadcast: " + blurwallpaperpath);
            SharedPreferences sf = context.getSharedPreferences("info", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sf.edit();
            editor.putString("wallpaper", blurwallpaperpath);
            editor.putInt("default", temp);
            editor.commit();
        } else if (ACTION_AB_WHITE_FIELD_ENTER.equals(action)) {
            Log.i("TAG", "onReceive: start");
            context.startActivity(new Intent(context, WhiteFieldActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        } else if (ACTION_AB_WHITE_FIELD_EXIT.equals(action)) {
            Log.i("TAG", "onReceive: stop");
            Activity target = WhiteFieldActivity.target.get();
            if (target != null) {
                target.finish();
            } else {
                Log.i("TAG", "onReceive: target is null");
            }
        } else if (ACTION_SHOW_SYSTEM_AUTIBURN.equals(action)) {
            // 防抖处理
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastBurnTime > BURN_DELAY) {
                lastBurnTime = currentTime;
                boolean isShow = SkgMultipleUsersManager.isAdminUser(context);
                if (isShow) {
                    MyWindowManager.showBurnView2(context);
                }
                android.util.Log.i(TAG, "onReceive: receive the showBurnView broadcast: "+isShow);
            } else {
                Log.d(TAG, "onReceive: 防抖，忽略ACTION_SHOW_SYSTEM_AUTIBURN广播");
            }

        }else if (ACTION_START_FREEZE.equals(action)){
            FreezeWindowManager.createFreezeCapture(context);
        }else if (ACTION_STOP_FREEZE.equals(action)){
            FreezeWindowManager.removeFreezeCapture(context);
        }else if (ACTION_FULL_SCREENSHOT.equals(action)){
            if (FullScreenShotActivity.isShoting) {
                Log.i(TAG, "ACTION_FULL_SCREENSHOT_______________ isShoting");
                return;
            }
            Log.i(TAG, "ACTION_FULL_SCREENSHOT_______________ unShoting starting");
            Intent newIntent = new Intent(ToolApplication.getInstance(), FullScreenShotActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ToolApplication.getInstance().startActivity(newIntent);

        } else if (ACTION_SHOW_GESTURE_SWIPEUP.equals(action)) {
            boolean shouldShow = SystemProperties.getBoolean(SHOW_GLOBAL_GESTURES, false);
            boolean isShowSreenlockState= SkgSettingsManager.getInstance().getScreenLockState();
            Log.d(TAG, "shouldShow = " + shouldShow+ "  isShowSreenlockState  ="+ isShowSreenlockState);
            if (shouldShow && !isShowSreenlockState) {
                GestureSwipeUpHelper.newInstance(context, intent).createGestureSwipeUpView();
            }
        } else if (ACTION_CLEAR_GESTURE_SWIPEUP.equals(action)) {
            GestureSwipeUpHelper.newInstance(context, intent).removeGestureSwipeUpView();
        }
    }


    //开机启动后，检测是否进入投屏器模式，解决开机2-4分钟内无法收到USB外设拔出广播
    private void checkProjectionMode(Context context) {
        //设置定时器检测投屏器设备，开机后五秒开始检测，每两秒检测一次，检测五分钟
        final int[] testTimes = {0};
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                UsbManager mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE); //这个只适用于Usb设备
                HashMap<String, UsbDevice> mDeviceMap = mUsbManager.getDeviceList();
                Log.i(TAG, "getCameraList testTimes[0] = " + testTimes[0]);
                if (mDeviceMap != null) {
                    boolean hasPapaProjection = false;
                    for (UsbDevice usbDevice : mDeviceMap.values()) {
                        if (isToofifiDevice(usbDevice)) {
                            hasPapaProjection = true;
                            break;
                        }
                    }
                    if (hasPapaProjection) {
                        SystemProperties.set(CAM_HUB_RESET_PROPERTY, CAM_HUB_PROPERTY_PERMIT);
                        startJudgeProjectMode(context);

                    } else {
                        SystemProperties.set(CAM_HUB_RESET_PROPERTY, CAM_HUB_PROPERTY_PREVENT);
                    }
                }
                //停止任务
                testTimes[0]++;
                if (testTimes[0] >= 5 * 60 / 2) {
                    timer.cancel();
                }
            }
        };
        timer.schedule(timerTask, 5 * 1000, 2000);
    }

    /**
     * @brief 判断是否为投屏器;
     * @date 2021/7/6
     * @param:UsbDevice:USB接入广播获取到的UsbDevice对象
     * @Sample usage:判断拔出的USB设备是否为toofifi，是的话将list中的摄像头遍历复位
     */
    private boolean isToofifiDevice(UsbDevice usbDevice) {
        boolean isTofifi = false;
        Log.i(TAG, "isToofifiDevice usbDevice.getProductName() = " + usbDevice.getProductName());

        if (usbDevice.getProductId() == 0x0878 && usbDevice.getVendorId() == 0x15a2) {
            isTofifi = true;
        }
        Log.i(TAG, "isToofifiDevice isTofifi = " + isTofifi);
        return isTofifi;
    }

    /**
     * @brief 复位cam所在2级hub及3级hub;
     * @date 2021/7/21
     */
    private void cam_hub_reset() {
        Log.i(TAG, "cam_hub_reset");
        SystemProperties.set(CAM_HUB_RESET_PROPERTY, "prevent");
    }

    /**
     * 检测投屏器模式，每两秒检测一次。
     * 投屏器设备存在的时候打开相机，吐司一次。
     */
    private synchronized void startJudgeProjectMode(Context context) {
        Log.i(TAG, "startJudgeProjectMode");
        if (mProjectionThread != null) {
            return;
        }
        mIsProjectionThreadRun = true;
        mProjectionThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (mIsProjectionThreadRun && !mProjectionThread.isInterrupted()) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "startJudgeProjectMode error = " + e.getMessage());
                    }
                    String type = SystemProperties.get(CAM_HUB_RESET_PROPERTY);
                    String openCamera = SystemProperties.get(CAM_HUB_CAMERA_PROPERTY);
                    Log.i(TAG, "startJudgeProjectMode type =  " + type + ",openCamera = " + openCamera);
                    if (CAM_HUB_PROPERTY_PERMIT.equalsIgnoreCase(type) && CAM_HUB_CAMERA_PROPERTY_OPEN.equalsIgnoreCase(openCamera)) {
                        Message message = Message.obtain();
                        message.what = MSG_TOAST;
                        message.obj = "" + context.getResources().getString(R.string.projection_mode);
                        mHandler.sendMessage(message);
                        SystemProperties.set(CAM_HUB_CAMERA_PROPERTY, "");
                    }
                }

            }
        });

        mProjectionThread.start();
    }

    /**
     * 停止投屏器状态监听
     */
    private void stopJudgeProjectMode(Context context) {
        Log.i(TAG, "stopJudgeProjectMode");
        mIsProjectionThreadRun = false;
        if (mProjectionThread != null) {
            mProjectionThread.interrupt();
            mProjectionThread = null;
        }
    }

    /**
     * @desc 判断是否有MIC;
     * @date 2020/12/15
     * @author:yonghong.liu
     */
    private boolean isAudioMicDevice(UsbDevice usbDevice) {
        boolean isAudio = false;
        int intefaceCount = usbDevice.getInterfaceCount();
        for (int ninterIndex = 0; !isAudio && ninterIndex < intefaceCount; ninterIndex++) {
            UsbInterface ntrface = usbDevice.getInterface(ninterIndex);
            if (ntrface.getInterfaceClass() == UsbConstants.USB_CLASS_AUDIO) {
                isAudio = true;
            }
        }
        return isAudio;
    }
}
